export class MathUtils {
  static toFixed = (value: number, digits: number) => value.toFixed(digits);
  static clamp = (value: number, min: number, max: number) => Math.min(Math.max(value, min), max);

  // 将角度转换为弧度
  static rotationRadians = (r: number) => (r * Math.PI) / 180;

  // 将弧度转换为角度
  static rotationDegrees = (r: number) => (r * 180) / Math.PI;

  static roundClamp = (value: number, min: number, max: number) =>
    Math.round(MathUtils.clamp(value, min, max));
  /* 吸附 */
  static snap = (value: number, step: number) => Math.round(value / step) * step;
  static sin = (r: number) => Math.sin(MathUtils.rotationRadians(r));
  static cos = (r: number) => Math.cos(MathUtils.rotationRadians(r));
  static tan = (r: number) => Math.tan(MathUtils.rotationRadians(r));
  static stepClamp = (params: { value: number; min: number; max: number; gap: number }): number => {
    const { gap, min, max, value } = params;
    // 计算步进调整后的值（以 0 为基准点）
    const stepValue = MathUtils.snap(value, gap);

    // 关键逻辑：单侧无限边界时，确保结果不小于 0
    if ((min === -Infinity && max === Infinity) || !min || !max) {
      return Math.max(stepValue, 0);
    }

    return MathUtils.clamp(stepValue, min, max);
  };
  static roundToStep = (value: number, gap: number = 1) => Math.round(value / gap) * gap;

  static lockAspectRatio(
    width: number,
    height: number,
    targetRatio: number
  ): { width: number; height: number } {
    const currentRatio = width / height;

    if (currentRatio < targetRatio) {
      return {
        width: height * targetRatio,
        height
      };
    }
    // 否则说明高度相对过大
    else {
      return {
        width,
        height: width / targetRatio
      };
    }
  }
  static getAngle(x1: number, y1: number, x2: number, y2: number) {
    const dx = x2 - x1;
    const dy = y2 - y1;
    return MathUtils.rotationDegrees(Math.atan2(dy, dx));
  }
  static normalizeRotation(rotate: number) {
    // 处理大于 360 度的情况，取模运算
    let positiveAngle = rotate % 360;

    // 如果结果为负数，加上 360 转为正数
    if (positiveAngle < 0) {
      positiveAngle += 360;
    }

    // 确保结果在 0 到 359 度之间
    // 处理特殊情况：当 rotate 是 360 的整数倍时，结果应为 0 而不是 360
    return positiveAngle === 360 ? 0 : positiveAngle;
  }
}
